import React from 'react';
import PropTypes from 'prop-types';

class AspectRatioImage extends React.Component {
  render() {
    return (
      <div
        style={{
          position: 'relative',
          width: '100%',
          overflow: 'hidden',
          ...this.props.style,
        }}
      >
        <div style={{ paddingTop: `${100 * this.props.ratio}%` }} />
        <div style={{ zIndex: 1, ...this.props.childrenStyle }}>
          {this.props.children}
        </div>
        <div
          style={{
            backgroundImage: `url(${this.props.image})`,
            backgroundSize: 'cover',
            left: 0,
            right: 0,
            top: 0,
            bottom: 0,
            position: 'absolute',
            zIndex: 0,
            ...this.props.imageStyle,
          }}
        />
      </div>
    );
  }
}

AspectRatioImage.propTypes = {
  image: PropTypes.string,
  ratio: PropTypes.number,
  imageStyle: PropTypes.object,
  childrenStyle: PropTypes.object,
};

AspectRatioImage.defaultProps = {
  image: null,
  ratio: 1,
  imageStyle: {},
  childrenStyle: {},
};

export default AspectRatioImage;